from django.http import HttpResponse, HttpRequest
from django.utils.deprecation import MiddlewareMixin
import json
import jwt
from mydjango.settings import SECRET_KEY


class UserMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        path = request.path_info
        if path.startswith('/login'):
            res = response.data
            print(res)
            encode_jwt = jwt.encode({'uid': res['uid']}, SECRET_KEY, algorithm='HS256')
            encode_str = str(encode_jwt, 'utf-8')
            return HttpResponse(json.dumps({
                'code': res['code'],
                'uid': encode_str,
                'username': res['username'],
                'data': res['data']
            }))
        return response
